/*
 Copyright 2011 and onwards Joao C. R. Pereira

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.
*/

#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "String.h"

String String_New(string str) {

  String so = NewObj(StringObj);

  Assert_NotNull(so);
  so->buffer = Buffer_New(strlen(str)+1, 255);
  strcpy((string)so->buffer->bytes, str);
  return so;
}

void String_Set(String so, string str) {

  Assert_NotNull(so);
  Buffer_EnsureCapacity(so->buffer, strlen(str)+1);
  strcpy((string)so->buffer->bytes, str);
}

string String_Get(String so) {
  
  Assert_NotNull(so);
  return (string)so->buffer->bytes;
}

void string_Dispose(string str) {

  Assert_NotNull(str);

  free(str);
}

string string_Clone(string str) {

  Assert_NotNull(str);

  string s = strdup(str);

  Assert_NotNull(s);
  return s;
} 

string string_Append(string str1, string str2) {

  Assert_NotNull(str1);
  Assert_NotNull(str2);

  string s = NewBytes(string, strlen(str1)+strlen(str2)+1);
  Assert_NotNull(s);

  strcpy(s, str1);
  strcat(s, str2);

  return s;
}

string string_Printf(string fmt, ...) {

  string s;
  va_list ap;
  
  va_start(ap, fmt);
  s = string_PrintfUnsafeVa(fmt, ap);
  Assert_NotNull(s);
  return s; 
}

string string_PrintfVa(string fmt, va_list ap) {

  string s;
  s = string_PrintfUnsafeVa(fmt, ap);
  Assert_NotNull(s);
  return s; 
}

string string_PrintfUnsafe(string fmt, ...) {

  string s;
  va_list ap;
  
  va_start(ap, fmt);
  s = string_PrintfUnsafeVa(fmt, ap);
  return s; 
}

string string_PrintfUnsafeVa(string fmt, va_list ap) {

  /* Guess we need no more than 100 bytes. */
  int n, size = 100;
  char *p, *np;
  
  if ((p = malloc(size)) == NULL)
    return NULL;
  
  while (1) {
    /* Try to print in the allocated space. */
    n = vsnprintf(p, size, fmt, ap);
    va_end(ap);
    /* If that worked, return the string. */
    if (n > -1 && n < size)
      return p;
    /* Else try again with more space. */
    if (n > -1)    /* glibc 2.1 */
      size = n+1; /* precisely what is needed */
    else           /* glibc 2.0 */
      size *= 2;  /* twice the old size */
    if ((np = realloc (p, size)) == NULL) {
      free(p);
      return NULL;
    } else {
      p = np;
    }
  }
}

